import axios from "axios";
import { nanoid } from "nanoid";
import { defineStore } from "pinia";

/* export const useTalkStore = defineStore("talk", {
  actions: {
    async getATalk() {
      // //发送请求
      let {
        data: { content: title },
      } = await axios.get("https://api.uomg.com/api/rand.qinghua?format=json");
      //把请求回来的字符串，转成一个对象对象
      let obj = { id: nanoid(), title }; //两种写法都可以 let obj = { id: nanoid(), title: title };
      //将对象(obj)放入数组(talkList)中
      this.talkList.unshift(obj);
    },
  },
  //真正存储数据的地方
  state() {
    return {
      //写 || [] 是为了防止当本地存储为null时转不了为对象时的报错
      talkList: JSON.parse(localStorage.getItem("talkList") as string) || [],
    };
  },
});   */

import { reactive } from "vue";
export const useTalkStore = defineStore("talk", () => {
  //talkList就是state
  const talkList = reactive(
    JSON.parse(localStorage.getItem("talkList") as string) || []
  );

  //getATalk相当于actions
  async function getATalk() {
    let {
      data: { content: title },
    } = await axios.get("https://api.uomg.com/api/rand.qinghua?format=json");
    let obj = { id: nanoid(), title };
    //放到数组中
    talkList.unshift(obj);
  }
  return { talkList, getATalk }; //用组合式state一定要return出去
});
